package com.js.blog.service.impl;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.js.blog.bean.User;
import com.js.blog.bean.vo.LoginVo;
import com.js.blog.bean.vo.UserVo;
import com.js.blog.dao.UserMapper;
import com.js.blog.service.UserService;
import com.js.blog.util.JwtAuthentication;
import com.js.blog.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yanglin
 * @create 2024-02-29 15:35 星期四
 * description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    
    @Override
    public UserVo login(LoginVo loginVo) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        //封装查询条件
        wrapper.eq(User::getPassword,MD5.encrypt(loginVo.getPassword()));
        wrapper.eq(User::getUsername,loginVo.getUsername());

        User user = userMapper.selectOne(wrapper);
        
        if (user == null){
            return null;
        }
        //生成token
        String token = JwtAuthentication.generateToken(user.getId());

        UserVo userVo = new UserVo();
        userVo.setId(user.getId());
        userVo.setUsername(user.getUsername());
        userVo.setPassword(user.getPassword());
        userVo.setCreateTime(user.getCreateTime());
        userVo.setToken(token);
        
        return userVo;
    }


    /**
     * 校验是否存在同名用户
     */
    @Override
    public boolean ifExistUsername(String username) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        List<User> users = userMapper.selectList(userLambdaQueryWrapper);
        if (users != null && users.size() != 0){
            return true;
        }
        return false;
    }
}
